package thread;

/**
 * Created with IntelliJ IDEA
 * Description
 * User：chenshu
 * Date：2023-11-01
 * Time：15:22
 */

import java.util.Random;

/**
 * 作业内容
 * 给定一个很长的数组 (长度 1000w), 通过随机数的方式生成 1-100 之间的整数.
 * 实现代码, 能够创建两个线程, 对这个数组的所有元素求和.
 * 其中线程1 计算偶数下标元素的和, 线程2 计算奇数下标元素的和.
 * 最终再汇总两个和, 进行相加
 * 记录程序的执行时间.
 */
public class Work1 {
    public static final int LENGTH = 1000_0000;
    public static long sum = 0;

    public static void serial() {
        Work1.sum = 0;
        Random rand = new Random();
        int[] arr = new int[LENGTH];
        for (int i = 0; i < arr.length; i++) {
            arr[i] = rand.nextInt(99) + 1;
        }
        long begin = System.currentTimeMillis();
        for (int i = 0; i < arr.length; i+=1) {
            sum += arr[i];
            Work1.sum += sum;
        }
        System.out.println(Work1.sum);

        long end = System.currentTimeMillis();

        System.out.println("调度时间为" + (end - begin) + "ms");
    }
    public static void concurrency() {
        Work1.sum = 0;
        Random rand = new Random();
        int[] arr = new int[LENGTH];
        for (int i = 0; i < arr.length; i++) {
            arr[i] = rand.nextInt(100) + 1;
        }

        long begin = System.currentTimeMillis();
        Thread t1 = new Thread(new Runnable() {
            @Override
            public void run() {
                long sum1 = 0;
                for (int i = 1; i < arr.length; i+=2) {
                    sum1 += arr[i];
                    Work1.sum += sum1;
                }
            }
        });

        Thread t2 = new Thread(new Runnable() {
            @Override
            public void run() {
                long sum2 = 0;
                for (int i = 0; i < arr.length; i+=2) {
                    sum2 += arr[i];
                    Work1.sum += sum2;
                }
            }
        });
        t1.start();
        t2.start();
        try {
            t1.join();
            t2.join();
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        }
        System.out.println(Work1.sum);
        long end = System.currentTimeMillis();
        System.out.println("调度时间为" + (end - begin) + "ms");

    }

    public static void main(String[] args) {
        concurrency();
    }
}
